const jwt = require("jsonwebtoken");

const { JWT_SECRET } = require("../config/config.default");
const {
  tokenExpiredError,
  invalidToken,
  hasNotAdminPermission,
} = require("../constant/err.type");

/**
 * 权限鉴定
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const auth = async (ctx, next) => {
  const { authorization = "" } = ctx.request.header;
  const token = authorization.replace("Bearer", "").trim();

  try {
    // user中包含payload的信息（id,user_name,is_admin）
    const user = jwt.verify(token, JWT_SECRET);
    // 注入到全局
    ctx.state.user = user;
  } catch (error) {
    console.log(error);
    switch (error.name) {
      case "TokenExpiredError":
        console.error("token已过期", error);
        return ctx.app.emit("error", tokenExpiredError, ctx);
      case "JsonWebTokenError":
        console.error("无效的token", error);
        return ctx.app.emit("error", invalidToken, ctx);
    }
  }
  await next();
};
/**
 * 是否管理员
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const hadAdminPermission = async (ctx, next) => {
  const { is_admin } = ctx.state.user;
  if (!is_admin) {
    console.log(ctx.request.files)
    return ctx.app.emit("error", hasNotAdminPermission, ctx);
  }
  await next();
};

module.exports = {
  auth,
  hadAdminPermission,
};
